package com.shuqi.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.common.FunctionsSwitch;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.StringUtils;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.interfaces.web.ShuqiWebJsBaseInterface;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 网页书城基类
 * 
 * @author li.li
 * 
 */
public abstract class BookCityWebBase extends ActivityBase implements OnClickListener {
    protected WebView mWebView;
    private LinearLayout layoutLoading;// 网络加载
    private TextView layoutLoadingPercent;// 网络加载进度
    private View netError;// 网络错误
    private CommonTitle title;// 标题
    private TextView retry;// 重试
    private String curUrl;
    private boolean isError;
    private ImageView noNetImage;
    protected Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 视图
        setContentView(contentView());
        // 初始化
        activityInitData();
        // 执行
        activityLogicForward();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!FunctionsSwitch.isOfferWallUpdate(this)) {
            // 消失红点
            title.setRightImage(R.drawable.bg_icon_offerwall_selector);
        }
    }


    /**
     * 视图资源
     * 
     * @return
     */
    protected abstract int contentView();

    @Override
    public void activityInitData() {
        mWebView = (WebView) findViewById(R.id.webview);
        layoutLoading = (LinearLayout) findViewById(R.id.include_loading);
        layoutLoadingPercent = (TextView) findViewById(R.id.tv_loading_percent);
        noNetImage = (ImageView) findViewById(R.id.nonet_image);

        netError = (LinearLayout) findViewById(R.id.include_error);
        retry = (TextView) findViewById(R.id.retry);
        title = (CommonTitle) findViewById(R.id.title);
        title.setImageListener(this);
        title.setStyle(true, false);

        if (FunctionsSwitch.isOfferWallOpen(this)) {
            title.setStyle(true, true);
            if (FunctionsSwitch.isOfferWallUpdate(this)) {
                title.setRightImage(R.drawable.bg_icon_offerwall_red_selector);// 显示红点
            }
        }

        retry.setOnClickListener(this);

        mWebView.setVisibility(View.VISIBLE);// 默认显示

        // 配置WebView
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setRenderPriority(RenderPriority.HIGH);
        // 缓存策略根据cache-control决定是否从网络上取数据,
        // 如果值为private、must-revalidate、max-age，则不会重访问，而如果为no-cache，则每次都重复访问
        // 例如：Cache-control: max-age=5，表示当访问此网页后的5秒内不会再次访问服务器
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

        mWebView.addJavascriptInterface(new ShuqiWebJavaScript<BookCityWebBase>(this),
                ShuqiWebJsBaseInterface.JS_OBJECT);

        // 下载处理
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                    String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                curUrl = url;
                start();

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                success();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                Util.loadUrl(BookCityWebBase.this, view, url);// 点击连接从自身打开
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description,
                    String failingUrl) {
                // 错误页面处理
                error();
            }



        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (layoutLoadingPercent != null) {
                    // layoutLoadingPercent.setVisibility(View.VISIBLE);
                    // layoutLoadingPercent.setText(progress + "%");
                }
            }
        });

        // 屏蔽复制
        mWebView.setOnLongClickListener(new WebView.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
    }

    @Override
    public void activityLogicForward() {}

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                gotoBookShelf();
                StatisticsUtils.onEvent(this, StatisticsEventID.BOOKSQUARE_TO_BOOKSHELF);
                break;
            case R.id.title_right:
                gotoOfferWall();
                StatisticsUtils.onEvent(this, StatisticsEventID.BOOKSQUARE_TO_OFW);
                break;
            case R.id.retry:// 重试
                // retry();
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        retry();

                    }
                });
                break;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView.canGoBack() && !isError) {
                mWebView.goBack();
                return true;
            } else {
                gotoBookShelf();
                return true;
            }

        }

        return super.onKeyDown(keyCode, event);
    }

    private void start() {
        layoutLoading.setVisibility(View.VISIBLE);
    }

    private void success() {
        if (layoutLoadingPercent != null)
            layoutLoadingPercent.setText("0%");
        
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                layoutLoading.setVisibility(View.GONE);
            }
        }, 1000);
    }

    private void error() {
        noNetImage.setImageResource(R.drawable.icon_wifi_loading_10);
        isError = true;
        mWebView.setVisibility(View.GONE);
        
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                layoutLoading.setVisibility(View.GONE);
                netError.setVisibility(View.VISIBLE);
            }
        }, 1000);
    }

    private void gotoBookShelf() {
        BookShelfActivity.showFromMainActivityGroup(this.getParent(), false);
    }

    private void gotoOfferWall() {
        Intent intent = new Intent(this.getParent(), OfferWallTopActivity.class);
        ActivityManager.getInstance().startNextActivity(intent, this.getParent());
    }

    private void retry() {

        // 重度组件
        NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

            @Override
            public void netErrorCallback() {
                doRetry();

            }
        });


    }

    private void doRetry() {
        if (mWebView != null && StringUtils.isNotBlank(curUrl)) {
            mWebView.stopLoading();
            mWebView.clearView();
            netError.setVisibility(View.GONE);
            mWebView.setVisibility(View.VISIBLE);
            mWebView.loadUrl(curUrl);
        }
    }

    // JS交互类
    private static final class ShuqiWebJavaScript<T extends BookCityWebBase> extends
            ShuqiWebJsBaseInterface {
        private T act;

        public ShuqiWebJavaScript(T act) {
            this.act = act;
        }

        @Override
        public void refresh() {
            act.retry();
        }

        @Override
        public Activity getActivity() {
            return act.getParent();
        }

        @Override
        public void loadError(String jsonData) {
            act.error();

        }

    }

}
